// Package dao @author dingrui @since 2021/11/26
package dao

import (
	"github.com/go-xorm/xorm"

	"github.com/bannirui/mini-prize/dal/model"
	"github.com/bannirui/mini-prize/datasource"
)

//
//  UserDayDao
//  @Description:
//
type UserDayDao struct {
	engine *xorm.Engine
}

var (
	// 单例
	G_userDayDao *UserDayDao
)

func init() {
	// 单例赋值
	G_userDayDao = &UserDayDao{engine: datasource.G_ormEngine}
}

//
//  GetById
//  @Description: 根据id查询
//  @receiver d
//  @param id
//  @return data
//
func (d *UserDayDao) GetById(id int) (data *model.UserDay) {
	var (
		ok  bool
		err error
	)
	data = &model.UserDay{Id: id}
	if ok, err = d.engine.Get(data); !ok || err != nil {
		data.Id = 0
	}
	return
}

//
//  PageAll
//  @Description: 分页查询所有
//  @receiver d
//  @param page
//  @param size
//  @return dataList
//
func (d *UserDayDao) PageAll(page, size int) (dataList []model.UserDay) {
	var (
		offset int
	)
	// 计算偏移
	offset = (page - 1) * size
	// 初始化切片
	dataList = make([]model.UserDay, 0)
	_ = d.engine.Desc("id").Limit(size, offset).Find(&dataList)
	return
}

//
//  CountAll
//  @Description: 计数
//  @receiver d
//  @return cnt
//
func (d *UserDayDao) CountAll() (cnt int64) {
	var (
		err error
	)
	if cnt, err = d.engine.Count(&model.UserDay{}); err != nil {
		cnt = 0
	}
	return
}

//
//  ListByUidAndDay
//  @Description: 根据uid和day查询所有
//  @receiver d
//  @param uid
//  @param day
//  @return dataList
//
func (d *UserDayDao) ListByUidAndDay(uid, day int) (dataList []model.UserDay) {
	// 初始化切片
	dataList = make([]model.UserDay, 0)
	_ = d.engine.Where("uid=?", uid).Where("day=?", day).Desc("id").Find(&dataList)
	return
}

//
//  GetCntByUidAndDay
//  @Description: 获取次数
//  @receiver d
//  @param uid
//  @param day
//  @return cnt
//
func (d *UserDayDao) GetCntByUidAndDay(uid, day int) (cnt int) {
	var (
		data *model.UserDay
		ok   bool
		err  error
	)
	data = &model.UserDay{}
	if ok, err = d.engine.Where("uid=?", uid).Where("day=?", day).Get(data); !ok || err != nil {
		cnt = 0
	} else {
		cnt = data.Cnt
	}
	return
}

//
//  Update
//  @Description: 更新
//  @receiver d
//  @param data
//  @param columns
//  @return err
//
func (d *UserDayDao) Update(data *model.UserDay, columns []string) (err error) {
	_, err = d.engine.Id(data.Id).MustCols(columns...).Update(data)
	return
}

//
//  InsertOne
//  @Description: 新增
//  @receiver d
//  @param data
//  @return err
//
func (d *UserDayDao) InsertOne(data *model.UserDay) (err error) {
	_, err = d.engine.Insert(data)
	return
}
